/**
 * Created by easy on 15/6/17.
 */
/**
 * Created by easy on 15/6/10.
 */
define(['MoCoop','service'],function (mc,service){
    //==审批类型
    var approvalChange = "5";//转审
    var approvalAgree = "1";//同意
    var approvalReject = "4";//驳回
    var approvalOpinion = "3";//意见
    var approvalBack = "";//撤回
    var approval = {
        approvalChange:approvalChange,
        approvalAgree:approvalAgree,
        approvalReject:approvalReject,
        approvalOpinion:approvalOpinion,
        approvalBack:approvalBack
    };
    approval.alert = function (message) {
        if (mc.developer === true ) {
            //alert(message);
        }
    };
    //如果审批要跳转到提交下一步页面，需保存审批信息到下个页面以使用
    //保存审批信息到本地存储
    approval.saveApprovalInfoToTemp = function (approvalInfo) {
        mc.manageTempData("set",function(){},"approvalInfo", JSON.stringify(approvalInfo));
    };
    //从本地存储获取审批信息
    approval.getApprovalInfoFromTemp = function (callback) {
        var getTempDataCallback = function(data){
            callback(JSON.parse(data.permanentData));
        };
        mc.manageTempData("get", getTempDataCallback, "approvalInfo");
    };

    //拼接审批options
    approval.combineApprovalOptions = function (options, approvalInfo) {
        switch (approvalInfo.performStat) {
            case approvalChange:
            {//转审
                //转审 下一步页面 已选择人员数组
                var getTurnPersonArray = function () {
                    var turnPersonArray = [];
                    var checkboxNum = $('.approvalchangeitem').length;
                    var turnPersonitem;
                    var approvalChangeItem;
                    for (var i = 1; i < (checkboxNum + 1); i++) {
                        approvalChangeItem = $('.approvalchangeitem:nth-child(' + i + ')');
                        if (approvalChangeItem.find('.ac-checkbox').hasClass('approvalcheckboxactive')) {
                            turnPersonitem = {
                                "turnValue": approvalChangeItem.attr('value'),
                                "type": approvalChangeItem.find('.approvalcheckboxactive-b').attr('value')
                            };
                            turnPersonArray.push(turnPersonitem);
                        }
                    }
                    return turnPersonArray;
                };
                var turnPersonList = getTurnPersonArray();
                if (turnPersonList.length === 0) {
                    mc.alert('请选择转审人', null);
                    return false;
                } else {
                    if (approvalInfo.approvalText === '' || approvalInfo.approvalText === undefined || approvalInfo.approvalText === null) {
                        approvalInfo.approvalText = '转候选人';
                    }
                    var freewfopts = [];
                    if ($('#freewfopts1').hasClass('approvalcheckboxactive')) {
                        freewfopts.push({"optValue": "1", "optKey": "freewfopts#1"});
                    }
                    if ($('#freewfopts2').hasClass('approvalcheckboxactive')) {
                        freewfopts.push({"optValue": "2", "optKey": "freewfopts#2"});
                    }
                    options = $.extend(options, {
                        "uid": "",
                        "toUid": "",
                        "touCodes": [],
                        "rMode": "",
                        "rejectToIdx": "",
                        "performExpl": approvalInfo.approvalText,
                        "turnPersonList": turnPersonList,
                        "freewfopts": freewfopts
                    });
                }
                break;
            }
            case approvalAgree:
            case approvalOpinion:
            {//同意
                //同意&意见 下一步页面 已选择人员数组
                var getSelectedPersonArray = function () {
                    var selectedPersonArray = [];
                    var checkboxNum = $('.approvalnext-personitem').length;
                    if (checkboxNum > 0) {
                        var personItem;
                        for (var i = 1; i < (checkboxNum + 1); i++) {
                            personItem = $('.approvalnext-personitem:nth-child(' + i + ')');
                            if (personItem.find('.approvalnext-checkbox').hasClass('approvalcheckboxactive')) {
                                selectedPersonArray.push(personItem.attr('value'));
                            }
                        }
                    }
                    return selectedPersonArray;
                };
                var selectedPersonArray = getSelectedPersonArray();
                var URL = window.location.toString();
                var isApprovalNextPage = (URL.indexOf("approval_next.html") > -1);//审批详情页
                if (selectedPersonArray.length === 0 && isApprovalNextPage && ($('.approvalnext-final').css("display") === "none")) {
                    mc.alert('请选择审批人', null);
                    return false;
                } else {
                    if (approvalInfo.approvalText === '' || approvalInfo.approvalText === undefined || approvalInfo.approvalText === null) {
                        if (approvalInfo.performStat === approvalAgree) {
                            approvalInfo.approvalText = '同意';
                        } else if (approvalInfo.performStat === approvalOpinion) {
                            approvalInfo.approvalText = '保留上报';
                        }
                    }
                    var approvalExtendObj = {
                        "rejectToIdx": "",
                        "performExpl": approvalInfo.approvalText
                    };
                    if (approvalInfo.approvalList !== null && approvalInfo.approvalList !== undefined) {
                        var seletedObj = approvalInfo.approvalList[approvalInfo.approvalListNum];
                        if (seletedObj.uid !== undefined) {
                            approvalExtendObj.uid = seletedObj.uid;
                        }
                        if (seletedObj.toUid !== undefined) {
                            approvalExtendObj.toUid = seletedObj.toUid;
                        }
                        if (seletedObj.rMode !== undefined) {
                            approvalExtendObj.rMode = seletedObj.rMode;
                        }
                        if (seletedObj.fromUid !== undefined) {
                            approvalExtendObj.fromUid = seletedObj.fromUid;
                        }
                    }
                    if($('.approvalnext-final').css("display") === "none"){
                        approvalExtendObj.touCodes = selectedPersonArray;
                    }

                    options = $.extend(options, approvalExtendObj);
                }

                break;
            }
            case approvalBack://撤回
                options = $.extend(options, {
                    "rejectToIdx": "",
                    "touCodes": [],
                    "uid": "",
                    "toUid": "",
                    "turnPersonList": [],
                    "fromUid": "",
                    "performExpl": "",
                    "rMode": ""
                });
                break;
            case approvalReject://驳回
                if (approvalInfo.approvalText === '' || approvalInfo.approvalText === undefined || approvalInfo.approvalText === null) {
                    approvalInfo.approvalText = '驳回';
                }
                var rejectToIdx = $('.approvalcheckboxactive').attr("value");
                options = $.extend(options, {
                    "touCodes": [],
                    "uid": "",
                    "toUid": "",
                    "turnPersonList": [],
                    "fromUid": "",
                    "rMode": "",
                    "performExpl": approvalInfo.approvalText,
                    "rejectToIdx": rejectToIdx
                });
                break;
        }
        return options;
    };
    approval.approvalSubmitAction = function (approvalInfo) {
        var options = {
            "performStat": approvalInfo.performStat,
            "taskId": approvalInfo.taskInfo.taskId,
            "sheetCode": approvalInfo.taskInfo.sheetCode,
            "uCode": approvalInfo.taskInfo.uCode,
            "idx": approvalInfo.taskInfo.idx,
            "userCode": mc.userInfo.userCode
        };
        options = approval.combineApprovalOptions(options, approvalInfo);

        if (options !== false) {
            var confirmSubmitCallback = function (result) {
                //点击确认
                if (result === 2) {
                    //调用原生notification显示提交中
                    mc.notification("提交中","Normal");
                    approval.alert("最终参数" + JSON.stringify(options));
                    var approvalSubmitCallback = function () {
                        // 调用原生notification显示审批成功
                        var message;
                        switch (approvalInfo.performStat) {
                            case approvalChange:
                            {//转审
                                message = "转审成功！";
                                break;
                            }
                            case approvalAgree://同意
                                message = "审批成功！";
                                break;
                            case approvalOpinion:
                            {//意见
                                message = "保留意见并上报成功！";
                                break;
                            }
                            case approvalBack://撤回
                                message = "撤回成功！";
                                break;
                            case approvalReject://驳回
                                message = "驳回成功！";
                                break;
                        }
                        mc.notification(message,"Succeed");
                        var URL = window.location.toString();
                        if(URL.indexOf("index.html") === -1){
                            setTimeout(function(){
                                mc.backToTargetPage("index.html");
                            },300);


                        }else{
                            if(approvalInfo.callback !== undefined){
                                approvalInfo.callback();
                            }

                        }
                    };

                    service.approvalSubmit(options, approvalSubmitCallback);
                }
            };
            var noticetext;
            switch (approvalInfo.performStat) {
                case approvalChange:
                {//转审
                    noticetext = "确认转审？";
                    break;
                }
                case approvalAgree://同意
                    noticetext = "确认同意？";
                    break;
                case approvalOpinion:
                {//意见
                    noticetext = "确认保留意见并上报？";
                    break;
                }
                case approvalBack://撤回
                    noticetext = "确认撤回该审批？";
                    break;
                case approvalReject://驳回
                    noticetext = "确认驳回？";
                    break;
            }
            mc.confirm(noticetext, confirmSubmitCallback);
        }
    };
    //执行转审，判断立即执行提交或进入下一步
    approval.approvalChangeImmediately = function (data, url, approvalInfo, callback) {
        approval.alert(JSON.stringify(data));
        var change = data.turn;
        if (change === null || change === undefined) {
            mc.alert("没有转审人信息，无法转审");
        } else {
            //进入下一页
            var changeList = change.turnPersonList;
            approval.alert(JSON.stringify(changeList));
            approvalInfo.approvalList = changeList;
            approval.saveApprovalInfoToTemp(approvalInfo);
            mc.jump(url,"转审");
        }
        callback();

    };
    //执行驳回,判断立即执行提交或进入下一步
    approval.approvalRejectImmediately = function (data, url, approvalInfo, callback) {
        approval.alert(JSON.stringify(data));
        var rejectList = data.rejectList;
        if (!rejectList || rejectList.length === 0) {
            mc.alert("没有驳回人信息，无法驳回");
        } else {
            //进入下一页
            approval.alert(JSON.stringify(rejectList));
            approvalInfo.approvalList = rejectList;
            approval.saveApprovalInfoToTemp(approvalInfo);
            mc.jump(url,'驳回');
        }
        callback();
    };
    //执行同意或意见,判断立即执行提交或进入下一步
    approval.approvalAgreeAndOpinionImmediately = function (data, url, approvalInfo, callback) {
        //common.alert(JSON.stringify(data));
        var submitList = data.submitList;
        if (!submitList || submitList.length === 0 || (submitList.length === 1 && (!submitList[0].touCodes || submitList[0].touCodes.length === 0))) {
            //直接提交
            approval.alert("直接提交");
            approvalInfo.approvalList = submitList;
            approvalInfo.approvalListNum = 0;
            approval.approvalSubmitAction(approvalInfo);
        } else {
            //进入下一页
            //common.alert(JSON.stringify(submitList));
            approvalInfo.approvalList = submitList;
            approval.saveApprovalInfoToTemp(approvalInfo);
            mc.jump(url,'提交到...');
        }
        callback();

    };

    //快捷审批
    approval.shortcutOfApproval = function (performStat, taskInfo, disabled,callback) {
        if (disabled !== "disabled") {
            var approvalInfo = {
                performStat:performStat,
                taskInfo:taskInfo,
                approvalText:"",
                callback:callback
            };
            approval.alert(JSON.stringify(approvalInfo));
            if (approvalInfo.performStat === approvalAgree) {//审批类型为同意
                //调用原生notification插件显示‘正在获取审批数据’
                mc.notification("正在获取审批数据","Normal");
                var options = {
                    taskId: approvalInfo.taskInfo.taskId,
                    idx: approvalInfo.taskInfo.idx,
                    performStat: approvalInfo.performStat,
                    wfCode: approvalInfo.taskInfo.wfCode,
                    wfUid: approvalInfo.taskInfo.wfUid
                };//生成请求参数
                var nextApprovalStepCallback = function (data) {//获得审批人列表
                    var url = "approval_next.html?performStat=" + performStat;
                    var approvalImmediatelyCallback = function () {
                        //判断可以立即执行审批后  调用关闭原生notification插件
                        mc.notification("","Close");
                    };
                    approval.approvalAgreeAndOpinionImmediately(data, url, approvalInfo, approvalImmediatelyCallback);//执行判断是否直接提交或跳转到提交下一步页面
                };
                service.getNextApprovalStepList(options, nextApprovalStepCallback);//从服务端获取审批人列表
            } else if (approvalInfo.performStat === approvalBack) {//审批类型为撤回
                approval.approvalSubmitAction(approvalInfo);//执行提交动作
            }

        }
    };
//执行审批动作
    approval.nextApprovalStep = function (performStat,taskInfo) {
        //调用原生notification插件显示‘正在获取审批数据’
        mc.notification("正在获取审批数据","Normal");

        var approvalText = $('#approvaltext').val();//获取审批意见
        var approvalInfo = {
            performStat:performStat,
            taskInfo:taskInfo,
            approvalText:approvalText
        };
        var options = {
            taskId: approvalInfo.taskInfo.taskId,
            idx: approvalInfo.taskInfo.idx,
            performStat: approvalInfo.performStat,
            wfCode: approvalInfo.taskInfo.wfCode,
            wfUid: approvalInfo.taskInfo.wfUid
        };//生成请求参数
        var nextApprovalStepCallback = function (data) {//获得审批人列表
            var approvalImmediatelyCallback = function () {
                //判断可以立即执行审批后  调用关闭原生notification插件
                mc.notification("","Close");
            };
            var url;
            if (performStat === approvalChange) {//审批类型为转审，设置url为approval-change.html
                url = "approval_change.html?performStat=" + performStat;
                approval.approvalChangeImmediately(data, url, approvalInfo, approvalImmediatelyCallback);
            }
            else if (performStat === approvalAgree || performStat === approvalOpinion) {//审批类型为同意或意见时，设置url为approval-next.html
                url = "approval_next.html?performStat=" + performStat;
                approval.approvalAgreeAndOpinionImmediately(data, url, approvalInfo, approvalImmediatelyCallback);
            }
            else if (performStat === approvalReject) {//审批类型为驳回时，设置url为approval-reject.html
                url = "approval_reject.html?performStat=" + performStat;
                approval.approvalRejectImmediately(data, url, approvalInfo, approvalImmediatelyCallback);
            }//执行判断是否直接提交或跳转到提交下一步页面
        };
        service.getNextApprovalStepList(options, nextApprovalStepCallback);//从服务端获取审批人列表

    };
    return approval;
});
